package com.sip.stream.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.media.MediaScannerConnection;
import android.util.Log;

import androidx.core.view.InputDeviceCompat;

import com.sip.stream.ClientApp;
import com.sip.stream.media.ZFYMediaManager;
import com.sip.stream.rxbus.RxBus;
import com.sip.stream.utils.zfy.RxBusTag;
import com.sip.stream.utils.zfy.ZFYExifInterTool;
import com.sip.stream.utils.zfy.ZFYMediaUtil;
import com.sip.stream.utils.zfy.event.ZFYMediaEvent;
import com.sip.stream.utils.zfy.osd.BitmapOSDTool;
import com.sip.stream.utils.zfy.osd.OSDToolFactory;
import com.sip.stream.utils.zfy.voice.BeepTool;
import com.sip.stream.utils.zfy.voice.BeepType;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class ImageSaver {
    private static final String TAG = ImageSaver.class.getSimpleName();
    private BitmapOSDTool caputreOSDTool;
    private ZFYMediaUtil zfyMediaUtil = new ZFYMediaUtil();


    public String saveJPEGImage(byte[] bArr, ZFYMediaEvent zFYMediaEvent) {
        FileOutputStream fileOutputStream;
        if (zFYMediaEvent != null) {
            RxBus.getDefault().post(zFYMediaEvent, RxBusTag.MEDIA_EVENT);
        }
        String newJpeg = this.zfyMediaUtil.getNewJpeg();
        if (newJpeg == null) {
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
        Bitmap decodeByteArray = BitmapFactory.decodeByteArray(bArr, 0, bArr.length);
        float captureDesWidth = ZFYMediaManager.getInstance().getConfig().getCaptureDesWidth() / decodeByteArray.getWidth();
        Log.i(TAG, "scale " + captureDesWidth);
        double d = (double) captureDesWidth;
        if (d < 1.1d && d > 0.9d) {
            if (!decodeByteArray.isMutable()) {
                decodeByteArray = Bitmap.createBitmap(decodeByteArray, 0, 0, decodeByteArray.getWidth(), decodeByteArray.getHeight(), (Matrix) null, true).copy(Bitmap.Config.ARGB_8888, true);
            }
        } else {
            Matrix matrix = new Matrix();
            matrix.postScale(captureDesWidth, captureDesWidth);
            try {
                Bitmap copy = Bitmap.createBitmap(decodeByteArray, 0, 0, decodeByteArray.getWidth(), decodeByteArray.getHeight(), matrix, true).copy(Bitmap.Config.ARGB_8888, true);
                decodeByteArray.recycle();
                decodeByteArray = copy;
            } catch (OutOfMemoryError e2) {
                e2.printStackTrace();
                decodeByteArray.recycle();
                return null;
            }
        }
        try {
            getCaputreOSDTool().addOSDDynamic(decodeByteArray);
        } catch (Exception e3) {
            e3.printStackTrace();
        }
        try {
            fileOutputStream = new FileOutputStream(newJpeg);
        } catch (IOException se) {
            fileOutputStream = null;
            se.printStackTrace();
        }
        try {
            try {
                decodeByteArray.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (Throwable th2) {
                th2.printStackTrace();
                if (fileOutputStream != null) {
                    try {
                        fileOutputStream.close();
                    } catch (IOException e6) {
                        e6.printStackTrace();
                    }
                }
            }
        } catch (Exception e7) {
            e7.printStackTrace();
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
            }
            decodeByteArray.recycle();
            ZFYExifInterTool.writeImageExif(newJpeg);
            scanFile(newJpeg);
            return newJpeg;
        }
        decodeByteArray.recycle();
        ZFYExifInterTool.writeImageExif(newJpeg);
        scanFile(newJpeg);
        return newJpeg;
    }


    public String saveNV21Image(byte[] bArr, ZFYMediaEvent zFYMediaEvent, int i, int i2) {
        Log.i(TAG, "saveNV21Image");
        Rect rect = new Rect(0, 0, i, i2);
        String newJpeg = this.zfyMediaUtil.getNewJpeg();
        if (newJpeg == null || newJpeg.isEmpty()) {
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
        try {
            new YuvImage(bArr, 17, rect.width(), rect.height(), null).compressToJpeg(rect, 100, new FileOutputStream(newJpeg));
            ZFYExifInterTool.writeImageExif(newJpeg);
            Log.i(TAG, "isNeedCapture saveImage 拍照保存成功");
            RxBus.getDefault().post(zFYMediaEvent, RxBusTag.MEDIA_EVENT);
            scanFile(newJpeg);
            return newJpeg;
        } catch (IOException e) {
            e.printStackTrace();
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
    }

    public String saveImage(byte[] bArr, ZFYMediaEvent zFYMediaEvent) {
        Log.i(TAG, "isNeedCapture saveImage");
        Rect rect = new Rect(0, 0, ZFYMediaManager.getInstance().getCameraParameters().getVideoWidth(), ZFYMediaManager.getInstance().getCameraParameters().getVideoHeight());
        String newJpeg = this.zfyMediaUtil.getNewJpeg();
        if (newJpeg == null || newJpeg.isEmpty()) {
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
        try {
            new YuvImage(bArr, 17, rect.width(), rect.height(), null).compressToJpeg(rect, 100, new FileOutputStream(newJpeg));
            ZFYExifInterTool.writeImageExif(newJpeg);
            Log.i(TAG, "isNeedCapture saveImage 拍照保存成功");
            if (zFYMediaEvent != null) {
                RxBus.getDefault().post(zFYMediaEvent, RxBusTag.MEDIA_EVENT);
            }
            scanFile(newJpeg);
            return newJpeg;
        } catch (IOException e) {
            e.printStackTrace();
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
    }

    public String saveImage(byte[] bArr, int i, int i2) {
        String str = TAG;
        Log.i(str, "isNeedCapture saveImage");
        Rect rect = new Rect(0, 0, i, i2);
        String newJpeg = this.zfyMediaUtil.getNewJpeg();
        if (newJpeg == null || newJpeg.isEmpty()) {
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
        try {
            new YuvImage(bArr, 17, rect.width(), rect.height(), null).compressToJpeg(rect, 100, new FileOutputStream(newJpeg));
            ZFYExifInterTool.writeImageExif(newJpeg);
            Log.i(str, "isNeedCapture saveImage 拍照保存成功");
            BeepTool.play(BeepType.CAPTURED);
            scanFile(newJpeg);
            return newJpeg;
        } catch (IOException e) {
            e.printStackTrace();
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
    }

    public String saveImage(byte[] bArr, String str, int i, int i2) {
        Rect rect = new Rect(0, 0, i, i2);
        if (str == null || str.isEmpty()) {
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
        try {
            new YuvImage(bArr, 17, rect.width(), rect.height(), null).compressToJpeg(rect, 100, new FileOutputStream(str));
            ZFYExifInterTool.writeImageExif(str, 8);
            scanFile(str);
            return str;
        } catch (IOException e) {
            e.printStackTrace();
            RxBus.getDefault().post(new ZFYMediaEvent("EVENT_TYPE_STORAGE_ABNORMAL"), RxBusTag.MEDIA_EVENT);
            return null;
        }
    }

    public BitmapOSDTool getCaputreOSDTool() {
        if (this.caputreOSDTool == null) {
            this.caputreOSDTool = OSDToolFactory.createBitmapOSDTool(ZFYMediaManager.getInstance().getOSDConfig());
        }
        return this.caputreOSDTool;
    }

    private static String covertLatToDMS(double d) {
        StringBuilder sb = new StringBuilder();
        float floor = (float) Math.floor(d);
        double d2 = d - floor;
        float floor2 = (float) Math.floor(60.0d * d2);
        sb.append(((int) floor) * 1000000);
        sb.append("/1000000,");
        sb.append(((int) floor2) * 100000);
        sb.append("/100000,");
        sb.append(((int) ((d2 * 3600.0d) - (60.0f * floor2))) * InputDeviceCompat.SOURCE_TRACKBALL);
        sb.append("/65540");
        return sb.toString();
    }

    private static String covertLongToDMS(double d) {
        StringBuilder sb = new StringBuilder();
        float floor = (float) Math.floor(d);
        double d2 = d - floor;
        float floor2 = (float) Math.floor(60.0d * d2);
        sb.append(((int) floor) * 100000);
        sb.append("/100000,");
        sb.append(((int) floor2) * InputDeviceCompat.SOURCE_TRACKBALL);
        sb.append("/65540,");
        sb.append(((int) ((d2 * 3600.0d) - (60.0f * floor2))) * 33685504);
        sb.append("/33685504");
        return sb.toString();
    }

    public void refreshOSDInfo() {
        BitmapOSDTool bitmapOSDTool = this.caputreOSDTool;
        if (bitmapOSDTool != null) {
            bitmapOSDTool.refreshOSDInfo();
        }
    }

    private void scanFile(String str) {
        MediaScannerConnection.scanFile(ClientApp.clientApp, new String[]{str}, new String[]{"image/jpeg"}, null);
    }

    private Bitmap toMutable(Bitmap bitmap) {
        Bitmap bitmap2 = null;
        try {
            File file = new File(ClientApp.clientApp.getExternalCacheDir() + "temp.jpeg");
            file.getParentFile().mkdirs();
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
            int width = bitmap.getWidth();
            int height = bitmap.getHeight();
            FileChannel channel = randomAccessFile.getChannel();
            MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0L, width * height * 4);
            bitmap.copyPixelsToBuffer(map);
            bitmap.recycle();
            bitmap2 = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            map.position(0);
            bitmap2.copyPixelsFromBuffer(map);
            channel.close();
            randomAccessFile.close();
            file.delete();
            return bitmap2;
        } catch (Exception e) {
            e.printStackTrace();
            return bitmap2;
        }
    }
}
